package com.greenline.pay.schedule.biz.task.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

public class DateUtils {
    private static final String DEFAULT_F = "yyyyMMdd";

    /**
     * 得到本周周一
     * 
     * @return yyyy-MM-dd
     */
    public static String getMondayOfThisWeek() {
        Calendar c = Calendar.getInstance();
        int dayofweek = c.get(Calendar.DAY_OF_WEEK) - 1;
        if (dayofweek == 0)
            dayofweek = 7;
        c.add(Calendar.DATE, -dayofweek + 1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(c.getTime());
    }

    /**
     * 得到本周周日
     * 
     * @return yyyy-MM-dd
     */
    public static String getSundayOfThisWeek() {
        Calendar c = Calendar.getInstance();
        int dayofweek = c.get(Calendar.DAY_OF_WEEK) - 1;
        if (dayofweek == 0)
            dayofweek = 7;
        c.add(Calendar.DATE, -dayofweek + 7);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(c.getTime());
    }

    public static Date addDay(int diff) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, diff);
        return calendar.getTime();
    }

    /**
     * 获取日期，格式为yyyy-MM-dd HH:mm:ss
     * 
     * @param d
     * @return String
     */
    public static String dateFormat(Date d, String format) {
        try {
            if (null == d) {
                return null;
            }
            if (StringUtils.isBlank(format)) {
                SimpleDateFormat defm = new SimpleDateFormat(DEFAULT_F);
                return defm.format(d);
            }
            SimpleDateFormat fm = new SimpleDateFormat(format);
            return fm.format(d);
        } catch (Exception e) {
        }
        return null;
    }
    
    /**
     * 在给定的时间上加指定的天数
     * 
     * @param startDate
     * @param diff
     * @return
     */
    public static Date addDay(Date startDate, int diff) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        calendar.add(Calendar.DAY_OF_MONTH, diff);
        return calendar.getTime();
    }
    
    public static Date getDateByString(String date, String format) {
        if (StringUtils.isNotBlank(date)) {
            try {
                if (StringUtils.isBlank(format)) {
                    SimpleDateFormat defm = new SimpleDateFormat(DEFAULT_F);
                    return defm.parse(date);
                }
                SimpleDateFormat fm = new SimpleDateFormat(format);
                return fm.parse(date);
            } catch (ParseException e) {
            }
        }
        return null;
    }

}
